#include "CPStdAfx.h"
#include "planeManager.h"
#include "Plane.h"
#include <sstream>

planeManager* planeManager::pm = NULL;
planeManager::planeManager(void)
:activePlane(NULL),planeIndex(0)
{

}

planeManager::~planeManager(void)
{

}
void planeManager::InitPlanes(int num,CKContext* context)
{
	if(num == 0)
		return;
	
	for(int i = 0; i<num; i++)
	{
		std::string pn = "plane0";
		std::stringstream ss;
		ss<<i;
		std::string pInt = ss.str();

		pn += pInt;

		Plane* p = createPlane(pn.c_str(),context);
		if(p)
		{
			p->setActiveState(false);
			_plantList[p->getName()] = p;
		}
		planeIndex+=1;
	}
}
planeManager& planeManager::Instance()
{
	if(pm == NULL)
		pm = new planeManager();
	return *pm;
}

Plane* planeManager::createPlane(const char* pn,CKContext* context)
{
	Plane* p = getPlaneByName(pn);

	if(p)
		return p;

   p = new Plane(pn,context,planeIndex);

   return p;
}

Plane* planeManager::getPlaneByName(const char* pn)
{
	std::map<std::string,Plane*>::const_iterator it = _plantList.find(pn);
	if(it != _plantList.end())
		return it->second;
	return NULL;
}

void planeManager::updataPlane()
{
// 	std::vector<Plane*>::iterator it = updataList.begin();
// 
// 	for(;it != updataList.end(); ++it)
// 	{
// 		if((*it)->isActive())
// 			(*it)->updata();
// 	}

    if(activePlane != NULL)
	activePlane->updata();
}
void planeManager::load()
{

}
void planeManager::save()
{

	
	CKObjectArray* o = CreateCKObjectArray();
	CKContext* ct = GetCKContext(0);

	CKCamera* cam = ct->GetPlayerRenderContext()->GetAttachedCamera();

	CKFile* f;
	f = ct->CreateCKFile();
	f->StartSave("plane.nmo");
	o->InsertRear(cam);

	std::map<std::string,Plane*>::iterator it = _plantList.begin();
	for (; it != _plantList.end(); ++it)
	{
		it->second->save(it->first.c_str(),o);
	}

	f->SaveObjects(o);
	f->EndSave();
	ct->DeleteCKFile(f);
	DeleteCKObjectArray(o);

	MessageBox(NULL,"save complete","save",MB_OK);
}

void planeManager::setActivePlane(Plane* p)
{
	if(p == NULL)
		return;

	 if(activePlane = p)
		 return;

	 if(activePlane != NULL)
		 activePlane->setActiveState(false);

	 p->setActiveState(true);

	 activePlane = p;
}

